package com.design.twords.utils;

import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;

import com.design.twords.config.ConfigData;

import java.io.IOException;

/**
 * Create by Alen
 * Time:  20:38
 */
public class MediaHelper {
    private static final String TAG = "MediaHelper";
    private static MediaPlayer mediaPlayer;

    //英式发音
    private static final int ENGLISH_VOICE = 1;
    //美式发音
    private static final int AMERICA_VOICE = 2;
    //默认为英式发音
    public static int DEFAULT_VOICE = ConfigData.getSong();

    // 有道英音发音
    public static final String YOU_DAO_VOICE_EN = "https://dict.youdao.com/dictvoice?type=1&audio=";
    // 有道美音发音
    public static final String YOU_DAO_VOICE_USA = "https://dict.youdao.com/dictvoice?type=0&audio=";

    public static void play(String wordName,int type){
        if(mediaPlayer!=null){
            releasePlayer();
        }
        mediaPlayer = new MediaPlayer();
        try {
            Uri uri = null;
            if(type == ENGLISH_VOICE) {
                uri = Uri.parse(YOU_DAO_VOICE_EN + wordName);
            } else{
                uri = Uri.parse(YOU_DAO_VOICE_USA + wordName);
            }
            mediaPlayer.setDataSource(MyApplication.getContext(),uri);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    //设置播放语速
                    //mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(2.0));
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if(mediaPlayer != null){
                        mediaPlayer.release();
                        mediaPlayer = null;
                    }
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    //重载play方法
    public static void play(String wordName){
        Log.d(TAG,"play: "+ wordName);
        wordName.replaceAll(" ","%20");
        int type = ConfigData.getSong();
        play(wordName,type);

    }

    public static void releasePlayer() {
        if(mediaPlayer != null){
            if(mediaPlayer.isPlaying()){
                mediaPlayer.stop();
            }
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

}
